import useMessage from '@/plugin/useMessage'
import {createUnit, getUnits, updateUnit,deleteUnit} from "@/api/modules/product";
import {defineStore} from "pinia";

export const useUnitsStore = defineStore('units', {
    state: () => ({
        data: [] as RelationItem[],
        loading: false,
        editorIndex: -1,
        createMode: false
    }),
    actions: {
        async getUnits() {
            this.loading = true
            const res = await getUnits()
            if (res.code === 200) {
                this.data = res.data
            }
            this.loading = false
        },
        async updateUnit(id: number, updatedData: any) {
            const res = await updateUnit(id, updatedData)
            if (res.code === 200) {
                const index = this.data.findIndex(unit => unit.id === id)
                if (index !== -1) {
                    this.data[index] = { ...this.data[index], ...updatedData }
                }
                this.editorIndex = -1
            }
            useMessage(res.code, res.message)
        },
        async createUnit(newData: any) {
            const res = await createUnit(newData)
            if (res.code === 200) {
                this.data.push(res.data)
                this.createMode = false
            }
            useMessage(res.code, res.message)
        },
        async deleteUnit(id: number) {
            const res = await deleteUnit(id)
            if (res.code === 200) {
                this.data = this.data.filter(item => item.id !== id)
            }
            useMessage(res.code, res.message)
        }
    },
    //开启持久化存储
    persist: true
})
export default useUnitsStore